#include "systime.h"
#include <string.h>
#include <assert.h>
#include <stdio.h>

#ifdef _WIN32 
#include <windows.h>

struct time_val {
	long tv_sec;
	long tv_usec;
};


// http://www.google.com/codesearch/p?hl=en#dR3YEbitojA/os_win32.c&q=GetSystemTimeAsFileTime%20license:bsd
static int gettimeofday(struct time_val *tv, void* tz) {
#define EPOCHFILETIME (116444736000000000ULL)
	FILETIME ft;
	LARGE_INTEGER li;
	uint64_t tt;
	GetSystemTimeAsFileTime(&ft);
	li.LowPart = ft.dwLowDateTime;
	li.HighPart = ft.dwHighDateTime;
	tt = (li.QuadPart - EPOCHFILETIME) / 10;
	tv->tv_sec = (long)(tt / 1000000u);
	tv->tv_usec = (long)(tt % 1000000u);

	return 0;
}
#undef EPOCHFILETIME


#else
#include <sys/time.h>
#endif // _WIN32

C_CODE_BEGIN

EXPORT_FUNC void ti_grab_time( struct systime* t ) {
#ifdef _WIN32
	struct time_val tv;
#else
	struct time_val tv;
#endif // _WIN32

	time_t tim;
	struct tm* des_t;
	assert(t);

	time(&tim);
	des_t =localtime(&tim);
	memcpy(&(t->des_ti),des_t,sizeof(struct tm));
	gettimeofday(&tv,NULL);
	t->usec = tv.tv_sec * 1000000u + tv.tv_usec;
}

EXPORT_FUNC int ti_print_time( const struct systime* ti, char* buffer , int sz ) {
	const char* ascstr = asctime( &(ti->des_ti) );
	char buf[1024];
	int esz = sprintf(buf,"%su-seconds:%llu",ascstr,ti->usec);
	if( esz <0 || esz >= sz )
		return -1;
	else {
		strcpy(buffer,buf);
	}
	return 1;
}

C_CODE_END